package com.gzhryc.shared_device.oem.h5.agent.controllers.api.v1.bxscn;

import com.gzhryc.common.ClassTools;
import com.gzhryc.common.StringTools;
import com.gzhryc.common.api.DefaultAPIResponse;
import com.gzhryc.servlet.DtoConstants;
import com.gzhryc.servlet.WebUtils;
import com.gzhryc.servlet.annotation.Route;
import com.gzhryc.shared_device.bxscn.code.dao.db.PortableEnergyCabinet;
import com.gzhryc.shared_device.bxscn.code.dao.db.PortableEnergyCabinetSlot;
import com.gzhryc.shared_device.bxscn.code.dao.enums.PortableEnergyCabinetEnum;
import com.gzhryc.shared_device.bxscn.code.services.PortableEnergyCabinetService;
import com.gzhryc.shared_device.bxscn.code.services.PortableEnergyCabinetSlotService;
import com.gzhryc.shared_device.bxscn.code.services.dto.PortableEnergyCabinetSearch;
import com.gzhryc.shared_device.bxscn.core.IBXSCNNetworkService;
import com.gzhryc.shared_device.bxscn.core.models.BXSCNExecuteResult;
import com.gzhryc.shared_device.bxscn.core.models.BXSCNOpenSlotCommand;
import com.gzhryc.shared_device.common.device.dao.db.Device;
import com.gzhryc.shared_device.common.device.services.DeviceService;
import com.gzhryc.shared_device.oem.code.HttpNetworkServiceUtils;
import com.gzhryc.shared_device.oem.code.agent.dao.db.AgentRelationDevice;
import com.gzhryc.shared_device.oem.code.agent.services.AgentRelationDeviceService;
import com.gzhryc.shared_device.oem.code.device.EDeviceFunCode;
import com.gzhryc.shared_device.oem.code.device.dao.models.AgentRelationBXSCNDevice;
import com.gzhryc.shared_device.oem.code.device.services.AgentRelationBXSCNDeviceService;
import com.gzhryc.shared_device.oem.code.device.services.dto.AgentRelationBXSCNDeviceSearch;
import com.gzhryc.shared_device.oem.code.user.ERoleType;
import com.gzhryc.shared_device.oem.h5.agent.ClientAPICodeConstants;
import com.gzhryc.shared_device.oem.h5.agent.LoginUser;
import com.gzhryc.shared_device.oem.h5.agent.WebConstants;
import com.gzhryc.shared_device.oem.h5.agent.dto.api.v1.bxscn.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

public class BXSCNDeviceController {

    @Route(value = "/agent/api/v1/bxscn/device/count.data")
    public BXSCNDeviceCountResponse deviceCount(HttpServletRequest request){
        BXSCNDeviceCountResponse apiResp = new BXSCNDeviceCountResponse(ClientAPICodeConstants.NULL_DATA, "暂无数据");
        LoginUser loginUser = WebUtils.getAttribute(request, WebConstants.ATTR_LOGIN_USER, LoginUser.class);
        if (loginUser != null) {
            if(ERoleType.Agent.index().equals(loginUser.getRoleType())) {
                PortableEnergyCabinetSearch search = new PortableEnergyCabinetSearch();
                search.setUserId(loginUser.getId());

                Long deviceCount = PortableEnergyCabinetService.self().countJoinBySearch(search);

                search.setDeploy(true);
                Long deployCount = PortableEnergyCabinetService.self().countJoinBySearch(search);

                search.setDeploy(null);
                search.setState(PortableEnergyCabinetEnum.State.Online.index());
                Long onlineCount = PortableEnergyCabinetService.self().countJoinBySearch(search);

                apiResp.setCode(ClientAPICodeConstants.SUCCESS,null);
                apiResp.getBody().setDeviceFunCodeName(EDeviceFunCode.BXSCN.note());
                apiResp.getBody().setDeviceCount(deviceCount);
                apiResp.getBody().setDeployCount(deployCount);
                apiResp.getBody().setOnlineCount(onlineCount);
            }else{
                AgentRelationBXSCNDeviceSearch search = new AgentRelationBXSCNDeviceSearch();
                search.setUserId(loginUser.getParentId());
                search.setRelationUserId(loginUser.getId());

                Long deviceCount = AgentRelationBXSCNDeviceService.self().countJoinBySearch(search);

                search.setDeploy(true);
                Long deployCount = AgentRelationBXSCNDeviceService.self().countJoinBySearch(search);

                search.setDeploy(null);
                search.setState(PortableEnergyCabinetEnum.State.Online.index());
                Long onlineCount = AgentRelationBXSCNDeviceService.self().countJoinBySearch(search);

                apiResp.setCode(ClientAPICodeConstants.SUCCESS,null);
                apiResp.getBody().setDeviceFunCodeName(EDeviceFunCode.BXSCN.note());
                apiResp.getBody().setDeviceCount(deviceCount);
                apiResp.getBody().setDeployCount(deployCount);
                apiResp.getBody().setOnlineCount(onlineCount);
            }
        }
        return apiResp;
    }

    @Route(value = "/agent/api/v1/bxscn/device/list.data")
    public BXSCNDeviceListResponse list(HttpServletRequest request) {
        BXSCNDeviceListResponse apiResp = new BXSCNDeviceListResponse(ClientAPICodeConstants.NULL_DATA, "暂无数据");
        BXSCNDeviceListRequest apiReq = WebUtils.getJsonRequest(request, BXSCNDeviceListRequest.class);
        if (apiReq != null) {
            Integer pageNo = apiReq.getBody().getPageNo() == null ? 1 : apiReq.getBody().getPageNo();
            Integer deployState = apiReq.getBody().getDeployState() == null ? 0 : apiReq.getBody().getDeployState();
            LoginUser loginUser = WebUtils.getAttribute(request, WebConstants.ATTR_LOGIN_USER, LoginUser.class);
            if (loginUser != null) {
                List<PortableEnergyCabinet> portableEnergyCabinetList = null;
                if(ERoleType.Agent.index().equals(loginUser.getRoleType())) {
                    PortableEnergyCabinetSearch search = new PortableEnergyCabinetSearch();
                    search.setUserId(loginUser.getId());
                    if(apiReq.getBody().getState() != null && apiReq.getBody().getState() > 0) {
                        search.setState(apiReq.getBody().getState());
                    }
                    search.setTrim(apiReq.getBody().getTrim());
                    if (deployState == 1) {
                        search.setDeploy(false);
                    } else if (deployState == 2) {
                        search.setDeploy(true);
                    }
                    portableEnergyCabinetList = PortableEnergyCabinetService.self().findJoinBySearch(search, pageNo, WebConstants.PAGE_LIMIT);
                }else{
                    AgentRelationBXSCNDeviceSearch search = new AgentRelationBXSCNDeviceSearch();
                    search.setUserId(loginUser.getParentId());
                    if(apiReq.getBody().getState() != null && apiReq.getBody().getState() > 0) {
                        search.setState(apiReq.getBody().getState());
                    }
                    search.setRelationUserId(loginUser.getId());
                    search.setTrim(apiReq.getBody().getTrim());
                    if (deployState == 1) {
                        search.setDeploy(false);
                    } else if (deployState == 2) {
                        search.setDeploy(true);
                    }
                    List<AgentRelationBXSCNDevice> data = AgentRelationBXSCNDeviceService.self().findJoinBySearch(search,pageNo, WebConstants.PAGE_LIMIT);
                    if(data != null && data.size() > 0){
                        portableEnergyCabinetList = new ArrayList<>();
                        for(AgentRelationBXSCNDevice item : data){
                            portableEnergyCabinetList.add(item);
                        }
                    }
                }

                if (portableEnergyCabinetList != null && portableEnergyCabinetList.size() > 0) {
                    apiResp.setCode(ClientAPICodeConstants.SUCCESS, null);
                    apiResp.getBody().setItems(new ArrayList<>());

                    List<String> deviceSnList = new ArrayList<>();
                    for (PortableEnergyCabinet portableEnergyCabinet : portableEnergyCabinetList) {
                        deviceSnList.add(portableEnergyCabinet.getDeviceSn());
                    }

                    List<PortableEnergyCabinetSlot> portableEnergyCabinetSlotList = PortableEnergyCabinetSlotService.self().findByDeviceSn(deviceSnList);
                    for (PortableEnergyCabinet portableEnergyCabinet: portableEnergyCabinetList) {
                        BXSCNDeviceListResponse.DeviceItem item = ClassTools.copy(new BXSCNDeviceListResponse.DeviceItem(), portableEnergyCabinet);
                        item.setStateName(portableEnergyCabinet.getStateName());
                        item.setPlaceId(portableEnergyCabinet.getDevice().getPlaceId());
                        item.setPlaceName(portableEnergyCabinet.getDevice().getPlaceName());
                        item.setPlaceAreaName(portableEnergyCabinet.getDevice().getAreaName());

                        Integer portableBatteryCount = 0;
                        if(portableEnergyCabinetSlotList != null && portableEnergyCabinetSlotList.size() > 0){
                            for(PortableEnergyCabinetSlot slot : portableEnergyCabinetSlotList){
                                if(portableEnergyCabinet.getDeviceSn().equals(slot.getDeviceSn()) && StringTools.isNotBlank(slot.getPortableBatterySn())){
                                    portableBatteryCount = portableBatteryCount + 1;
                                }
                            }
                        }
                        item.setPortableBatteryCount(portableBatteryCount);
                        apiResp.getBody().getItems().add(item);
                    }
                }
            }
        }
        return apiResp;
    }

    @Route(value = "/agent/api/v1/bxscn/device/info.data")
    public BXSCNDeviceInfoResponse info(HttpServletRequest request) {
        BXSCNDeviceInfoResponse apiResp = new BXSCNDeviceInfoResponse(ClientAPICodeConstants.NULL_DATA, "暂无数据");
        BXSCNDeviceInfoRequest apiReq = WebUtils.getJsonRequest(request, BXSCNDeviceInfoRequest.class);
        if (apiReq != null && StringTools.isNotBlank(apiReq.getBody().getDeviceSn())) {
            LoginUser loginUser = WebUtils.getAttribute(request, WebConstants.ATTR_LOGIN_USER, LoginUser.class);
            if (loginUser != null) {
                Device device = DeviceService.self().getByDeviceSn(apiReq.getBody().getDeviceSn());
                if (device != null) {
                    if (device.getUserId() == null) {
                        apiResp.setCode(ClientAPICodeConstants.NOT_POWER, "无权限查看");
                        return apiResp;
                    }else if(ERoleType.Agent.index().equals(loginUser.getRoleType())){
                        if(!device.getUserId().equals(loginUser.getId())){
                            apiResp.setCode(ClientAPICodeConstants.NOT_POWER, "无权限查看");
                            return apiResp;
                        }
                    }else {
                        AgentRelationDevice agentRelationDevice = AgentRelationDeviceService.self().getByKeys(loginUser.getParentId(),loginUser.getId(),device.getDeviceSn());
                        if(agentRelationDevice == null){
                            apiResp.setCode(ClientAPICodeConstants.NOT_POWER, "无权限查看");
                            return apiResp;
                        }
                    }

                    PortableEnergyCabinet energyCabinet = PortableEnergyCabinetService.self().getByDeviceSn(device.getDeviceSn());
                    if(energyCabinet != null){
                        apiResp.setCode(ClientAPICodeConstants.SUCCESS,null);
                        ClassTools.copy(apiResp.getBody(),energyCabinet);

                        apiResp.getBody().setSlotItems(new ArrayList<>());

                        apiResp.getBody().setPlaceId(device.getPlaceId());
                        apiResp.getBody().setPlaceName(device.getPlaceName());

                        List<PortableEnergyCabinetSlot> slotList = PortableEnergyCabinetSlotService.self().findJoinByDeviceSn(energyCabinet.getDeviceSn());
                        for(int i = 1;i <= energyCabinet.getSlotTotal();i++) {
                            BXSCNDeviceInfoResponse.SlotItem slotItem = new BXSCNDeviceInfoResponse.SlotItem();
                            slotItem.setSlotNum(i);

                            if(slotList != null && slotList.size() > 0){
                                for(PortableEnergyCabinetSlot slot : slotList){
                                    if(slot.getSlotNum().equals(i)){
                                        slotItem.setPortableBattery(slot.getPortableBatterySn());
                                        slotItem.setState(slot.getState());
                                        slotItem.setStateName(slot.getStateName());
                                        break;
                                    }
                                }
                            }
                            apiResp.getBody().getSlotItems().add(slotItem);
                        }
                    }
                }
            }
        }
        return apiResp;
    }

    @Route(value = "/agent/api/v1/bxscn/device/operate/eject.do")
    public DefaultAPIResponse eject(HttpServletRequest request) {
        DefaultAPIResponse apiResp = new DefaultAPIResponse(ClientAPICodeConstants.EXECUTE_ERROR, "开仓指定仓室失败");
        BXSCNOperateEjectTestRequest apiReq = WebUtils.getJsonRequest(request, BXSCNOperateEjectTestRequest.class);
        if (apiReq != null && StringTools.isNotBlank(apiReq.getBody().getDeviceSn()) && apiReq.getBody().getSlotNum() != null) {
            PortableEnergyCabinet energyCabinet = PortableEnergyCabinetService.self().getByDeviceSn(apiReq.getBody().getDeviceSn());
            if (energyCabinet != null) {
                IBXSCNNetworkService networkService = HttpNetworkServiceUtils.getBXSCNNetworkService(energyCabinet.getIotNodeId());
                if (networkService != null) {
                    BXSCNOpenSlotCommand command = new BXSCNOpenSlotCommand();
                    command.setDeviceSn(apiReq.getBody().getDeviceSn());
                    command.setSlotNum(apiReq.getBody().getSlotNum());

                    BXSCNExecuteResult executeResult = networkService.openSlot(command);
                    if (executeResult != null) {
                        if (BXSCNExecuteResult.SUCCESS.equals(executeResult.getCode())) {
                            apiResp.setCode(DtoConstants.SUCCESS, null);
                        } else if (StringTools.isNotBlank(executeResult.getMsg())) {
                            apiResp.setMsg(executeResult.getMsg());
                        } else {
                            apiResp.setMsg("发送命令失败");
                        }
                    } else {
                        apiResp.setMsg("便携式电池网络服务无响应");
                    }
                } else {
                    apiResp.setMsg("未获取便携式电池网络服务");
                }
            }
        }
        return apiResp;
    }
}
